package com.example.runningman.friend;

import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.example.runningman.MainActivity;
import com.example.runningman.R;
import com.example.runningman.bean.Art;
import com.example.runningman.bean.Img;
import com.example.runningman.bean.Remark;
import com.example.runningman.dao.PointsDao;
import com.example.runningman.database.BaiduPointsDatebase;
import com.example.runningman.fragment.FileUtil;
import com.example.runningman.fragment.ProfileFragment;
import com.example.runningman.util.EmojiUtil;
import com.example.runningman.util.GlideBlurTransformation;
import com.example.runningman.util.SPUtil;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.example.runningman.util.BitmapUtil.compressImage;

public class WritActivity extends AppCompatActivity implements View.OnClickListener {
    ImageView back;
    Button start;
    EditText cont_et;
    ImageView imageView1;
    ImageView imageView2;
    ImageView imageView3;
    ImageView imageView4;
    ImageView imageView5;
    ImageView imageView6;
    ImageView imageView7;
    ImageView imageView8;
    ImageView imageView9;
    List<Img> list_img=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_writ);
        back=findViewById(R.id.back);
        start=findViewById(R.id.fabiao);
        cont_et=findViewById(R.id.conte);
        imageView1=findViewById(R.id.img1);
        imageView2=findViewById(R.id.img2);
        imageView3=findViewById(R.id.img3);
        imageView4=findViewById(R.id.img4);
        imageView5=findViewById(R.id.img5);
        imageView6=findViewById(R.id.img6);
        imageView7=findViewById(R.id.img7);
        imageView8=findViewById(R.id.img8);
        imageView9=findViewById(R.id.img9);
        back.setOnClickListener(this);
        start.setOnClickListener(this);
        imageView1.setOnClickListener(this);
        imageView2.setOnClickListener(this);
        imageView3.setOnClickListener(this);
        imageView4.setOnClickListener(this);
        imageView5.setOnClickListener(this);
        imageView6.setOnClickListener(this);
        imageView7.setOnClickListener(this);
        imageView8.setOnClickListener(this);
        imageView9.setOnClickListener(this);

        mHandler=new Mhandler();

    }
    Gson gson=new Gson();
    @Override
    public void onClick(View v) {
        Intent intentToPickPic;
        switch (v.getId()){
            case R.id.back:
                Intent intent = new Intent(WritActivity.this, MainActivity.class);
                startActivity(intent);
                break;
            case R.id.img1:
                intentToPickPic = new Intent(Intent.ACTION_PICK, null);
                intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");

                startActivityForResult(intentToPickPic, 1);
                break;
            case R.id.img2:
                intentToPickPic = new Intent(Intent.ACTION_PICK, null);
                intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");

                startActivityForResult(intentToPickPic, 2);
                break;
            case R.id.img3:
                intentToPickPic = new Intent(Intent.ACTION_PICK, null);
                intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");

                startActivityForResult(intentToPickPic, 3);
                break;
            case R.id.img4:
                intentToPickPic = new Intent(Intent.ACTION_PICK, null);
                intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");

                startActivityForResult(intentToPickPic, 4);
                break;
            case R.id.img5:
                intentToPickPic = new Intent(Intent.ACTION_PICK, null);
                intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");

                startActivityForResult(intentToPickPic, 5);
                break;
            case R.id.img6:
                intentToPickPic = new Intent(Intent.ACTION_PICK, null);
                intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");

                startActivityForResult(intentToPickPic, 6);
                break;
            case R.id.img7:
                intentToPickPic = new Intent(Intent.ACTION_PICK, null);
                intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");

                startActivityForResult(intentToPickPic, 7);
                break;
            case R.id.img8:
                intentToPickPic = new Intent(Intent.ACTION_PICK, null);
                intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");

                startActivityForResult(intentToPickPic, 8);
                break;
            case R.id.img9:
                intentToPickPic = new Intent(Intent.ACTION_PICK, null);
                intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");

                startActivityForResult(intentToPickPic, 9);
                break;
            case  R.id.fabiao:
                if("".equals(cont_et.getText().toString())) {
                    Toast.makeText(getApplicationContext(),"请输入内容",Toast.LENGTH_SHORT).show();
                }else {
                    postBaidu(cont_et.getText().toString());

                }
                break;
        }
    }
    private Mhandler mHandler;


    private  class Mhandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==1){
                String ReturnMessage = (String) msg.obj;
                Log.i("获取的返回信息",ReturnMessage);

                Img img= new Img();
                img.setImgurl(ReturnMessage);
                list_img.add(img);
                /***
                 * 在此处可以通过获取到的Msg值来判断
                 * 给出用户提示注册成功 与否，以及判断是否用户名已经存在
                 */

            }
            if(msg.what==2){
                String ReturnMessage = (String) msg.obj;
                Log.i("获取的返回信息",ReturnMessage);

                    Intent intent1 = new Intent("android.intent.action.CART_BROADCAST");
                    intent1.putExtra("data","refresh");
                    LocalBroadcastManager.getInstance(WritActivity.this).sendBroadcast(intent1);
                    sendBroadcast(intent1);
                    Intent intent = new Intent(WritActivity.this,MainActivity.class);
                    startActivity(intent);

            }
            if(msg.what==3){
                String conclusion = (String) msg.obj;
                Log.e("213", conclusion);
                if (conclusion.equals("合规")) {
                    Art art = new Art();
                    art.setUserid(SPUtil.getInstance(getApplicationContext()).getString("useid"));
                    art.setUsername(SPUtil.getInstance(getApplicationContext()).getString("username"));
                    art.setPhotoUrl(SPUtil.getInstance(getApplicationContext()).getString("photo","http://120.26.177.58:8080/upload/h_head.png"));
                    Date date=new Date(System.currentTimeMillis());
                    art.setCreatetime(date.toString());
                    try {
                        art.setContent(EmojiUtil.emojiConvert(cont_et.getText().toString()));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    String s= gson.toJson(art);
                    String d=gson.toJson(list_img);
                    postRequest(s,d);
                } else {
                    Toast.makeText(WritActivity.this, "存在敏感词汇，发布失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, final Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        Uri uri;
        String filePath;
        switch (requestCode) {
            case 1:
                uri = data.getData();
                filePath = FileUtil.getFilePathByUri(WritActivity.this, uri);
                filePath = compressImage(filePath);
                if (!TextUtils.isEmpty(filePath)) {
                    //将照片显示在 ivImage上
                    Glide.with(WritActivity.this).load(filePath)
                            .apply(RequestOptions.bitmapTransform(new GlideBlurTransformation(WritActivity.this)))
                            .into(imageView1);
                    imageView2.setVisibility(View.VISIBLE);
                    postRequest(filePath);
                }
                break;
            case 2:
                uri = data.getData();
                filePath = FileUtil.getFilePathByUri(WritActivity.this, uri);
                filePath = compressImage(filePath);
                if (!TextUtils.isEmpty(filePath)) {
                    //将照片显示在 ivImage上
                    Glide.with(WritActivity.this).load(filePath)
                            .apply(RequestOptions.bitmapTransform(new GlideBlurTransformation(WritActivity.this)))
                            .into(imageView2);
                    imageView3.setVisibility(View.VISIBLE);
                    postRequest(filePath);
                }
                break;

            case 3:
                uri = data.getData();
                filePath = FileUtil.getFilePathByUri(WritActivity.this, uri);
                filePath = compressImage(filePath);
                if (!TextUtils.isEmpty(filePath)) {
                    //将照片显示在 ivImage上
                    Glide.with(WritActivity.this).load(filePath)
                            .apply(RequestOptions.bitmapTransform(new GlideBlurTransformation(WritActivity.this)))
                            .into(imageView3);
                    imageView4.setVisibility(View.VISIBLE);
                    postRequest(filePath);
                }
                break;
            case 4:
                uri = data.getData();
                filePath = FileUtil.getFilePathByUri(WritActivity.this, uri);
                filePath = compressImage(filePath);
                if (!TextUtils.isEmpty(filePath)) {
                    //将照片显示在 ivImage上
                    Glide.with(WritActivity.this).load(filePath)
                            .apply(RequestOptions.bitmapTransform(new GlideBlurTransformation(WritActivity.this)))
                            .into(imageView4);
                    imageView5.setVisibility(View.VISIBLE);
                    postRequest(filePath);
                }
                break;
            case 5:
                uri = data.getData();
                filePath = FileUtil.getFilePathByUri(WritActivity.this, uri);
                filePath = compressImage(filePath);
                if (!TextUtils.isEmpty(filePath)) {
                    //将照片显示在 ivImage上
                    Glide.with(WritActivity.this).load(filePath)
                            .apply(RequestOptions.bitmapTransform(new GlideBlurTransformation(WritActivity.this)))
                            .into(imageView5);
                    imageView6.setVisibility(View.VISIBLE);
                    postRequest(filePath);
                }
                break;
            case 6:
                uri = data.getData();
                filePath = FileUtil.getFilePathByUri(WritActivity.this, uri);
                filePath = compressImage(filePath);
                if (!TextUtils.isEmpty(filePath)) {
                    //将照片显示在 ivImage上
                    Glide.with(WritActivity.this).load(filePath)
                            .apply(RequestOptions.bitmapTransform(new GlideBlurTransformation(WritActivity.this)))
                            .into(imageView6);
                    imageView7.setVisibility(View.VISIBLE);
                    postRequest(filePath);
                }
                break;
            case 7:
                uri = data.getData();
                filePath = FileUtil.getFilePathByUri(WritActivity.this, uri);
                filePath = compressImage(filePath);
                if (!TextUtils.isEmpty(filePath)) {
                    //将照片显示在 ivImage上
                    Glide.with(WritActivity.this).load(filePath)
                            .apply(RequestOptions.bitmapTransform(new GlideBlurTransformation(WritActivity.this)))
                            .into(imageView7);
                    imageView8.setVisibility(View.VISIBLE);
                    postRequest(filePath);
                }
                break;
            case 8:
                uri = data.getData();
                filePath = FileUtil.getFilePathByUri(WritActivity.this, uri);
                filePath = compressImage(filePath);
                if (!TextUtils.isEmpty(filePath)) {
                    //将照片显示在 ivImage上
                    Glide.with(WritActivity.this).load(filePath)
                            .apply(RequestOptions.bitmapTransform(new GlideBlurTransformation(WritActivity.this)))
                            .into(imageView8);
                    imageView9.setVisibility(View.VISIBLE);
                    postRequest(filePath);
                }
                break;
            case 9:
                uri = data.getData();
                filePath = FileUtil.getFilePathByUri(WritActivity.this, uri);
                filePath = compressImage(filePath);
                if (!TextUtils.isEmpty(filePath)) {
                    //将照片显示在 ivImage上
                    Glide.with(WritActivity.this).load(filePath)
                            .apply(RequestOptions.bitmapTransform(new GlideBlurTransformation(WritActivity.this)))
                            .into(imageView9);

                    postRequest(filePath);
                }
                break;
        }
    }
    final OkHttpClient client = new OkHttpClient();
    private void postRequest(String filePath)  {
        //建立请求表单，添加上传服务器的参数
        Log.e("sss", filePath);
        String fileName=filePath.substring(filePath.lastIndexOf("."));
        RequestBody formBody = new MultipartBody.Builder()
                .addFormDataPart("file", fileName,
                        RequestBody.create(MediaType.parse("multipart/form-data"), new File(filePath)))
                .build();
        //发起请求
        final Request request = new Request.Builder()
                .url("http://120.26.177.58:8080/AndroidServer01/addUserImg?")
                .post(formBody)
                .build();
        //新建一个线程，用于得到服务器响应的参数
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    //回调
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                        mHandler.obtainMessage(1, response.body().string()).sendToTarget();

                    } else {
                        throw new IOException("Unexpected code:" + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
    private void postRequest(String art,String imgs)  {
        //建立请求表单，添加上传服务器的参数

        //建立请求表单，添加上传服务器的参数
        RequestBody formBody = new FormBody.Builder()
                .add("article",art)
                .add("imgs", imgs)
                .build();
        //发起请求
        final Request request = new Request.Builder()
                .url("http://120.26.177.58:8080/AndroidServer01/addArt?")
                .post(formBody)
                .build();
        //新建一个线程，用于得到服务器响应的参数
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    //回调
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                        mHandler.obtainMessage(2, response.body().string()).sendToTarget();

                    } else {
                        throw new IOException("Unexpected code:" + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
    private void postBaidu(String text) {
        //建立请求表单，添加上传服务器的参数

        RequestBody formBody = new FormBody.Builder()
                .add("access_token", "24.7ec06635d6a1fa0ec5b001fef0cf1d76.2592000.1591175866.282335-19718698")
                .add("text", text)
                .build();
        //发起请求
        final Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?")
                .post(formBody)
                .build();
        //新建一个线程，用于得到服务器响应的参数
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    //回调
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                        String s = response.body().string();
                        String conclusion = "合格";
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            conclusion = jsonObject.getString("conclusion");


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        mHandler.obtainMessage(3, conclusion).sendToTarget();



                    } else {
                        throw new IOException("Unexpected code:" + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

